/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.drone.com;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import fr.uha.ensisa.jmp.drone.app.DroneConstants;


public class UDPConnection extends ComInterface
{
	private DatagramSocket socket;
	private int port;
	private byte[] receiveBuffer;
	private DatagramPacket receivePacket;
	private ByteBuffer receibeByteBuffer;

	public UDPConnection(int port, int bufferSize) throws SocketException, UnknownHostException, BadInterfaceException
	{
		super();
		this.port = port;
		//this.socket = new DatagramSocket(port, localAddress);
		this.socket = new DatagramSocket(port);

		this.socket.setSoTimeout(DroneConstants.UDP_TIMEOUT);
		
		this.receiveBuffer = new byte[bufferSize];
		this.receivePacket = new DatagramPacket(this.receiveBuffer, receiveBuffer.length, droneAddress, this.port);
		this.receibeByteBuffer = ByteBuffer.wrap(this.receiveBuffer).order(ByteOrder.LITTLE_ENDIAN);
	}
	
	public void send(byte[] sendBuffer) throws IOException
	{
		DatagramPacket packet= new DatagramPacket(sendBuffer, sendBuffer.length, droneAddress, this.port);
		this.socket.send(packet);
	}
	
	public ByteBuffer receive() throws IOException
	{
		this.receibeByteBuffer.clear();
		this.socket.receive(this.receivePacket);
		return this.receibeByteBuffer;
	}	
	
	public void close()
	{
		this.socket.close();
	}
}